import { baseUrl } from '../../../utils/config'
const { get, post } = require('../../../utils/request.js')
const EventBus = require('../../../utils/eventBus.js')

wx.onBeforePageUnload(() => {
  EventBus.emit('setting.checkFamilyInfo')
})

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    show: false,
    duration: 300,
    position: 'bottom',
    round: true,
    overlay: true,
    baseUrl: baseUrl,
    totalAmount: 98,
    outTradeNo: '',
    costWays: [{
      year: 1,
      cost: 98,
      active: true
    }, {
      year: 2,
      cost: 178,
      active: false
    }, {
      year: 3,
      cost: 238,
      active: false
    }],
    childrens: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.freshData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  freshData() {
    get('family/list', {
      "filter_unicode_eq_s": wx.getStorageSync('unicode'),
      "filter_memberAlias_notIn_ss": '爸爸,妈妈',
      "orderBy": "birthday",
      "joinDomain": "bankAccount"
    }, (data) => {
      if (data && data.length > 0) {
        data[0].active = true
      }
      this.setData({
        childrens: data
      })
    })
  },
  selectedCard({ currentTarget: { id } }) {
    this.data.childrens[id].active = !this.data.childrens[id].active;
    const childCount = this.data.childrens.filter(item => item.active).length;

    if (childCount != 0) {
      this.setData({
        childrens: this.data.childrens
      })
      this.calulateTotalMoney();
    } else {
      this.data.childrens[id].active = !this.data.childrens[id].active;
    }
  },
  chooseYear({ currentTarget: { id } }) {
    this.data.costWays.forEach((item) => {
      item.active = false;
    })
    this.data.costWays[id].active = true;

    this.setData({
      costWays: this.data.costWays
    })

    this.calulateTotalMoney();
  },
  calulateTotalMoney() {
    const childCount = this.data.childrens.filter(item => item.active).length;

    if (childCount == 0) {
      wx.showToast({
        title: '请选择人',
        icon: 'error',
        duration: 2000
      });
      return;
    }
    const costYearPer = this.data.costWays.filter(item => item.active)[0];
    const costPer = costYearPer.cost;
    const totalMoney = childCount * costPer;
    this.setData({
      totalAmount: totalMoney
    })
  },
  updateOutTrandeNo(trandeNo) {
    this.setData({
      outTradeNo: trandeNo
    })
  },
  risePay() {
    const activeChild = this.data.childrens.filter(item => item.active);
    const costYearPer = this.data.costWays.filter(item => item.active)[0];
    const familyIds = activeChild.map(item => item.id).join(",");
    const bankCardIds = activeChild.map(item => item.bankAccount.id).join(",");
    const params = {
      //TODO 测试支付
      totalMoney: 0.01,
      // totalMoney: this.data.totalAmount,
      years: costYearPer.year,
      yearPrice: costYearPer.cost,
      familyIdList: familyIds,
      bankCardIdList: bankCardIds,
      description: '续费儿童卡'
    }

    post('weixin/rise/pay/order', params, ({ timeStamp, nonceStr, packageStr, signType, paySign, outTradeNo }) => {
      this.setData({
        outTradeNo: outTradeNo
      })
      wx.requestPayment({
        timeStamp: timeStamp,
        nonceStr: nonceStr,
        package: packageStr,
        signType: signType,
        paySign: paySign,
        success(res) {
          //支付成功后，更新到期时间
          post('bankaccount/paysuccess', {
            years: params.years,
            ids: params.bankCardIdList,
            outTradeNo: outTradeNo,
            payStatus: 'SUCCESS'
          }, () => {
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 2000,
            })
            EventBus.emit('home.freshAllData')
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/tabBar/setting/me',
              })
            }, 2000);
          });
        }, fail({ errMsg }) {
          if (errMsg != "requestPayment:fail cancel") {
            get('bankaccount/payerror',
              { outTradeNo: outTradeNo });
            wx.showToast({
              title: '支付失败',
              icon: 'success',
              duration: 2000,
            })
          }
        }
      })

    })
  },
  queryPay() {
    post('weixin/queryOrderStatus',
      { outTradeNo: this.data.outTradeNo },
      (data) => {
        console.log(data)
      })
  },
  refundOrder() {

  },
  clickPrivacy() {
    wx.navigateTo({
      url: '/pages/me/privacy/privacy',
    })
  },
  changeCheckedPrivacy() {
    this.setData({
      checked: !this.data.checked
    })
  },
  readyPay() {
    this.setData({
      show: true,
      checked: false
    })
  },
  cancelPay() {
    this.setData({
      show: false
    })
  },
  confimAddReply() {
    if (!this.data.checked) {
      wx.showToast({
        title: '请先同意用户协议',
        icon: 'error',
        duration: 2000,
      })
    } else {
      this.setData({
        show: false
      })
      this.risePay();
    }
  }
})